<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.type" filterable placeholder="类型" class="filter-item" @change="getList" clearable style="width:10%">
        <el-option label="判断题" value="judge"></el-option>
        <el-option label="单选题" value="one_choose"></el-option>
        <el-option label="多选题" value="choose"></el-option>
      </el-select>
      <el-select v-model="listQuery.cate_id" filterable placeholder="请选择工种" class="filter-item" @change="getList"
                 clearable style="margin-left:5px;width:10%"
      >
        <el-option
          v-for="item in pcate"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-select v-model="listQuery.level" filterable placeholder="级别" class="filter-item" @change="getList" clearable  style="margin-left:5px;width:10%">
        <el-option
          v-for="item in levelList"
          :key="item.level"
          :label="item.label"
          :value="item.level">
        </el-option>
      </el-select>
      <el-input
        class="filter-item"
        placeholder="输入关键字进行过滤"
        v-model="listQuery.keyword"
        style="width: 20%;margin-left:5px"
      >
      </el-input>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                 style="margin-left: 10px"
      >
        搜索
      </el-button>
      <el-button class="filter-item" type="success" @click="handleCreate"
                 style="margin-left: 10px"
      >
        添加
      </el-button>
      <el-upload
        style="float: right;margin-right:10px;margin-top:5px"
        class="upload-demo"
        ref="upload"
        :action="'/api/excel/import?cid='+listQuery.cate_id+'&lid='+listQuery.level"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :before-remove="beforeRemove"
        multiple
        :limit="10"
        :on-exceed="handleExceed"
        :auto-upload="false"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      </el-upload>
    </div>
    <el-checkbox-group v-model="checkedIds" @change="handleCheckedIdsChange">
      <el-table v-loading="listLoading" :data="list" :key="tableKey" border fit highlight-current-row
                style="width: 100%"
      >
        <el-table-column align="center" label="ID" width="80">
          <template slot-scope="{row}">
            <el-checkbox :key="row.id" :label="row.id"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column min-width="80px" align="center" label="工种">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.cate_name }}</el-tag>
            <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
          </template>
        </el-table-column>

        <el-table-column width="100px" align="center" label="题型">
          <template slot-scope="scope">
            <el-tab-pane label="判断题" name="judge"></el-tab-pane>
            <el-tab-pane label="单选题" name="one_choose"></el-tab-pane>
            <el-tab-pane label="多选题" name="choose"></el-tab-pane>
            <el-tag effect="plain" v-if="scope.row.type == 'judge'">判断题</el-tag>
            <el-tag effect="plain" v-else-if="scope.row.type == 'one_choose'">单选题</el-tag>
            <el-tag effect="plain" v-else="scope.row.type == 'choose'">多选题</el-tag>
            <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
          </template>
        </el-table-column>
<!--        <el-table-column min-width="80px" align="center" label="状态">-->
<!--          <template slot-scope="scope">-->
<!--            <el-switch-->
<!--              v-model="scope.row.status"-->
<!--              :active-value="1"-->
<!--              :inactive-value="0"-->
<!--              @change="changeStatus($event,scope.row.id)"-->
<!--            >-->
<!--            </el-switch>-->
<!--            &lt;!&ndash;          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>&ndash;&gt;-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column min-width="80px" align="center" label="题干">
          <template slot-scope="scope">
            {{ scope.row.stem }}
            <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
          </template>
        </el-table-column>

        <el-table-column min-width="80px" align="center" label="分数">
          <template slot-scope="scope">
            {{ scope.row.score }}
            <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
          </template>
        </el-table-column>

<!--        <el-table-column min-width="120px" align="center" label="难度">-->
<!--          <template slot-scope="scope">-->
<!--            <el-rate-->
<!--              v-model="scope.row.difficulty"-->
<!--              :texts="text"-->
<!--              disabled-->
<!--              show-text-->
<!--              text-color="#ccc"-->
<!--              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"-->
<!--            >-->
<!--            </el-rate>-->
<!--          </template>-->
<!--        </el-table-column>-->

        <el-table-column min-width="80px" align="center" label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.created_at }}</span>
            <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="120">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)">

            </el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="del(scope.row.id)">

            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-checkbox-group>
    <el-divider>
      <el-checkbox :indeterminate="isIndeterminate" style="margin-left:10px;" v-model="checkAll"
                   @change="handleCheckAllChange"
      >全选
      </el-checkbox>
      <el-button size="mini" type="success" round style="margin-left:10px;" @click="handleClickExport">导出excel
      </el-button>
    </el-divider>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="form" label-width="80px" :rules="rules">
        <el-tabs v-model="activeName" @tab-click="handleClick" style="margin-left:3%" :disabled="dialogStatus == 'update'">
          <el-tab-pane label="判断题" name="judge"></el-tab-pane>
          <el-tab-pane label="单选题" name="one_choose"></el-tab-pane>
          <el-tab-pane label="多选题" name="choose"></el-tab-pane>
<!--          <el-tab-pane label="简答题" name="easy"></el-tab-pane>-->
<!--          <el-tab-pane label="名词解释" name="explain"></el-tab-pane>-->
<!--          <el-tab-pane label="论述题" name="essay"></el-tab-pane>-->
<!--          <el-tab-pane label="计算题" name="calculate"></el-tab-pane>-->
        </el-tabs>
        <el-form-item label="选择题库" prop="cate_id">
          <el-select v-model="form.cate_id" filterable placeholder="请选择" class="filter-item"
                     clearable style="margin-left:5px;"
                     :disabled="dialogStatus == 'update'"
          >
            <el-option
              v-for="item in pcate"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择等级" prop="level">
          <el-select v-model="form.level" filterable placeholder="级别" class="filter-item" clearable
                     :disabled="dialogStatus == 'update'"
                     style="margin-left:5px;width:180px">
            <el-option
              v-for="item in levelList"
              :key="item.level"
              :label="item.label"
              :value="item.level">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="题干:" prop="stem">
          <el-input v-model="form.stem" :rows="1" type="textarea" class="article-textarea" autosize
                    placeholder="请输入内容"
          />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
        </el-form-item>
        <el-form-item label="选项" v-if="activeName == 'judge'">
          <el-radio v-model="form.answer" label="A">正确</el-radio>
          <el-radio v-model="form.answer" label="B">错误</el-radio>
        </el-form-item>
        <el-form-item label="选项" v-if="activeName == 'choose' || activeName == 'one_choose'">
<!--          <el-tag-->
<!--            :key="tag"-->
<!--            v-for="tag in dynamicTags"-->
<!--            closable-->
<!--            :disable-transitions="false"-->
<!--            effect="plain"-->
<!--            @close="handleClose(tag)">-->
<!--          </el-tag>-->
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
<!--          </el-checkbox-group>-->
          <el-button v-else class="button-new-tag" size="small" @click="showInput">增加选项</el-button>
          <el-divider v-if="dynamicTags.length>0"><font style="color:#ccc;font-size:12px">选项内容(选中即为正确答案)</font></el-divider>
          <el-checkbox-group v-model="answer" style="margin-left:10px">
            <el-checkbox v-for="(item,index) in dynamicTags" :key="index" :label="item" style="width:100%">
              <el-link v-if="index == 0" type="primary">A:{{item}} </el-link>
              <el-link v-if="index == 1" type="primary">B: {{item}}</el-link>
              <el-link v-if="index == 2" type="primary">C: {{item}}</el-link>
              <el-link v-if="index == 3" type="primary">D: {{item}}</el-link>
              <el-link v-if="index == 4" type="primary">E: {{item}}</el-link>
              <el-button style="margin-left:30px;margin-top:-5px" size="mini" icon="el-icon-delete" @click="handleClose(item,index)">
              </el-button>
            </el-checkbox>
          </el-checkbox-group>
          <el-divider v-if="dynamicTags.length>0"><font style="color:#ccc;font-size:12px">选项数:({{dynamicTags.length}})</font></el-divider>
        </el-form-item>
<!--        <el-form-item label="状态">-->
<!--          <el-switch-->
<!--            v-model="form.status"-->
<!--            :active-value="1"-->
<!--            :inactive-value="0"-->
<!--          ></el-switch>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="难易度">-->
<!--          <el-rate-->
<!--            style="margin-top:10px"-->
<!--            text-color="#ccc"-->
<!--            :texts="text"-->
<!--            v-model="form.difficulty"-->
<!--            show-text-->
<!--            :colors="colors">-->
<!--          </el-rate>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="特殊资源">-->
<!--          <el-radio-group v-model="form.resource">-->
<!--            <el-radio label="线上品牌商赞助"></el-radio>-->
<!--            <el-radio label="线下场地免费"></el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
        <el-form-item label="正确答案" v-if="activeName != 'choose' && activeName != 'one_choose' && activeName != 'judge'">
          <el-input type="textarea" v-model="form.a"></el-input>
        </el-form-item>
        <el-form-item label="分数" prop="score" >
          <el-input-number  :precision="1" :step="0.5" v-model="form.score" :min="0" :max="9999" label="分数" size="small"></el-input-number><font color="#ccc" style="margin-left:10px">分数</font>
        </el-form-item>
<!--        <el-form-item label="答案解析">-->
<!--          <el-input type="textarea" v-model="form.parsing"></el-input>-->
<!--        </el-form-item>-->
        <center>
          <el-button type="primary" @click="createData">提交</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </center>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import store from '@/store'
import router from '@/router'
import { cateAll, changeStatus, getList,createQuestion ,del } from '@/api/questions' // Secondary package based on el-pagination

export default {
  name: 'CompanyExcel',
  components: { Pagination },
  filters: {
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 100) {
        return value.slice(0, 100) + '...'
      }
      return value
    },
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      activeName:'choose',
      pcate: [],
      listQuery: {
        page: 1,
        limit: 20,
        keyword: '',
        cate_id: undefined,
        type:'',
        level:''
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      dialogFormVisible: false,
      dialogStatus: '',
      fileList: [],
      checkAll: false,
      checkedIds: [],
      idOptions: [],
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      isIndeterminate: true,
      form: {
        id: undefined,
        cate_id:undefined,
        stem: '',
        answer:[],
        // difficulty:undefined,
        // parsing:'',
        type: undefined,
        options:undefined,
        status:0,
        a:'',
        b:'',
        c:'',
        d:'',
        e:'',
        score:0,
        level:''
      },
      levelList:[
        {
          level: 1,
          label: '高级技师'
        }, {
          level: 2,
          label: '技师'
        },
        {
          level: 3,
          label: '高级'
        }, {
          level: 4,
          label: '中级'
        },
        {
          level: 5,
          label: '初级'
        }
      ],
      answer:[],
      iconClasses: ['icon-rate-face-1', 'icon-rate-face-2', 'icon-rate-face-3'],
      text: ['入门', '初级', '中等', '困难', '灾难'],
      rules: {
        stem: [{ required: true, message: '题干不能为空', trigger: 'blur' }],
        cate_id: [{ required: true, message: '请选择工种', trigger: 'blur' }],
        level: [{ required: true, message: '请选择职业等级', trigger: 'blur' }],
        score: [{ required: true, message: '请填写分数', trigger: 'blur' }]
      }
    }
  },
  computed: {
    contentShortLength() {
      return this.form.stem.length
    }
  },
  created() {
    const id = this.$route.query.cid
    if(id){
      this.listQuery.cate_id = parseInt(id)
    }
    this.getList()
    this.getPcate()
  },
  methods: {
    handleClose(tag,index) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      this.form.a = ''
      this.form.b = ''
      this.form.c = ''
      this.form.d = ''
      this.form.e = ''
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        if(this.dynamicTags.length <= 4){
          this.dynamicTags.push(inputValue)
        }
        else{
         this.$message.info('选项最多可添加四个')
        }
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    handleClick(tab, event) {
      this.dynamicTags = []
      this.answer = []
      this.resetTemp()
    },
    getPcate() {
      cateAll().then(response => {
        this.pcate = response.data
        // Just to simulate the time of the request
      })
    },
    handleRemove(file, fileList) {

    },
    handlePreview(file) {

    },
    handleExceed(files, fileList) {
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleSuccess(file, fileList) {
      this.getList()
    },
    submitUpload() {
      if(!this.listQuery.cate_id || !this.listQuery.level){
        this.$message.info('请先选择工种和等级')
        return ''
      }
      this.$refs.upload.submit()
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleCheckAllChange(val) {
      this.checkedIds = val ? this.idOptions : []
      this.isIndeterminate = false
    },
    handleCheckedIdsChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.idOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.idOptions.length
    },
    handleClickExport() {
      if (this.checkedIds.length < 1) {
        this.$message('您尚未选中要导出的数据，请先选择')
        return
      }
      let json = JSON.stringify(this.checkedIds)
      window.open('/api/excel/export?data=' + json)
      // downMembers(this.checkedIds).then(response => {
      //
      // })
    },
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
        this.checkAll = false
        this.idOptions = []
        this.checkedIds = []
        for (var i in this.list) {
          this.idOptions[i] = this.list[i].id
        }
      })
    },
    changeStatus(val, id) {
      changeStatus(val, id).then(response => {
        this.$notify.success({
          title: '消息提示',
          message: response.msg,
          offset: 100
        })
      })
    },
    resetTemp() {
      this.form = {
        id: undefined,
        cate_id:undefined,
        stem: '',
        answer:[],
        // difficulty:undefined,
        // parsing:'',
        type: undefined,
        options:undefined,
        status:0,
        a:'',
        b:'',
        c:'',
        d:'',
        e:'',
        score:0.0,
        level:''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      if(this.activeName == 'choose' || this.activeName == 'one_choose'){
        this.form.options = this.dynamicTags.length
        if(this.dynamicTags.length <= 0){
          this.$message.info('请先填写选项')
          return ''
        }
        for(var i in this.dynamicTags){
          if(i == 0){
            this.form.a = this.dynamicTags[i]
          }else if( i == 1){
            this.form.b = this.dynamicTags[i]
          }
          else if( i == 2){
            this.form.c = this.dynamicTags[i]
          }
          else if ( i == 3){
            this.form.d = this.dynamicTags[i]
          }else{
            this.form.e = this.dynamicTags[i]
          }
        }
        this.form.answer = ''
        for(var i in this.answer){
          var key =  this.dynamicTags.indexOf(this.answer[i])
          if(key == 0) {
            this.form.answer +='A,'
          }else if(key == 1){
            this.form.answer +='B,'
          }else if(key == 2){
            this.form.answer +='C,'
          }else{
            this.form.answer +='D,'
          }
        }
        this.form.answer= this.form.answer.slice(0,this.form.answer.length-1)
      }
      if(this.activeName == 'judge'){
        this.form.options = 2
      }
      if(this.form.answer.length <= 0){
        this.$message.info('请先勾选正确答案')
        return ''
      }
      this.form.type = this.activeName
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createQuestion(this.form).then(response => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            if (response.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.resetTemp()
              this.getList()
            } else {
              this.$notify.error({
                title: '失败',
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      // console.dir(row)
      this.activeName = row.type
      this.dynamicTags = []
      this.answer = []
      if(this.activeName == 'choose' || this.activeName == 'one_choose'){
         if(row.a && row.a.length > 0){
           this.dynamicTags.push(row.a)
         }
        if(row.b && row.b.length > 0){
          this.dynamicTags.push(row.b)
        }
        if(row.c && row.c.length > 0){
          this.dynamicTags.push(row.c)
        }
        if(row.d && row.d.length > 0){
          this.dynamicTags.push(row.d)
        }
        let arr =[]
        if(row.answer.length > 0){
          arr = row.answer.split(',')
        }
        for(var i in arr){
          if(arr[i] == 'A'){
            this.answer.push(this.dynamicTags[0])
          }else if(arr[i] == 'B'){
            this.answer.push(this.dynamicTags[1])
          }else if(arr[i] == 'C'){
            this.answer.push(this.dynamicTags[2])
          }else{
            this.answer.push(this.dynamicTags[3])
          }
        }
      }
      this.dialogStatus = 'update'
       this.dialogFormVisible = true
       this.form = Object.assign({}, row) // copy obj
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    del(id) {
      this.$confirm('确认要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(response => {
          // this.list.unshift(this.temp)
          if (response.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
          } else {
            this.$notify.error({
              title: '失败',
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}

.el-tooltip__popper {
  max-width: 60%;
}

.el-tooltip__popper, .el-tooltip__popper.is-dark {
  background: rgb(48, 65, 86) !important;
  color: #fff !important;
  line-height: 24px;
}
</style>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 60%;
  /*margin-left: 10px;*/
  vertical-align: bottom;
}
</style>
